<template>
	<view class="page">
		<!-- 步骤指示器 -->
		<view class="step-indicator">
			<view class="step-item" :class="[ activeIndex1==0?'active':'']" >
				<view class="step-number">1</view>
				<text class="step-text">填写信息</text>
			</view>
			<view class="step-item" :class="[ activeIndex1 ==1?'active':'']">
				<view class="step-number">2</view>
				<text class="step-text">签署协议</text>
			</view>
			<view class="step-item" :class="[ activeIndex1==2?'active':'']">
				<view class="step-number">3</view>
				<text class="step-text">签署完成</text>
			</view>
		</view>
		<view v-if="formData?.status == 1" style="display: flex;justify-content: center;flex-direction: column;align-items: center;margin-top: 150px;">
			<wd-icon name="check-circle-filled" color="#67C23A" size="48px"></wd-icon>
			<span style="color: #67C23A;padding-top: 10px;">已签署完成</span>
		</view>
		<!-- 表单区域 -->
		<view class="form-section" v-if="formData?.status == 0 && activeIndex1== 0">
			<!-- 姓名 -->
			<view class="form-item">
				<view class="label">
					<text class="label-text">姓名</text>
					<text class="required">*</text>
				</view>
				<view class="input-wrapper">
					<input 
						class="input-field"
						v-model="formData.name"
						placeholder="请输入姓名"
						@blur="validateField('name')"
					/>
				</view>
				<view v-if="errors.name" class="error-text">{{ errors.name }}</view>
			</view>
			
			<!-- 手机号码 -->
			<view class="form-item">
				<view class="label">
					<text class="label-text">手机号码</text>
					<text class="required">*</text>
				</view>
				<view class="input-wrapper">
					<input 
						class="input-field"
						v-model="formData.phone"
						placeholder="请输入手机号码"
						type="number"
						maxlength="11"
						@blur="validateField('phone')"
					/>
				</view>
				<view v-if="errors.phone" class="error-text">{{ errors.phone }}</view>
			</view>
			
			<!-- 身份证号码 -->
			<view class="form-item">
				<view class="label">
					<text class="label-text">身份证号码</text>
					<text class="required">*</text>
				</view>
				<view class="input-wrapper">
					<input 
						class="input-field"
						v-model="formData.idcard"
						placeholder="请输入身份证号码"
						maxlength="18"
						@blur="validateField('idcard')"
					/>
				</view>
				<view v-if="errors.idcard" class="error-text">{{ errors.idcard }}</view>
			</view>
			
			<!-- 性别 -->
			<view class="form-item">
				<view class="label">
					<text class="label-text">性别</text>
					<text class="required">*</text>
				</view>
				<view class="input-wrapper" @click="show3=true">
					<view class="input-field2">
						{{formData.sex?(formData.sex==2?'女':'男'):'请选择性别'}}
					</view>
				</view>
				<view v-if="errors.sex" class="error-text">{{ errors.sex }}</view>
			</view>
			<!-- 紧急联系人 -->
			<view class="form-item">
				<view class="label">
					<text class="label-text">紧急联系人</text>
					<text class="required">*</text>
				</view>
				<view class="input-wrapper">
					<input 
						class="input-field"
						v-model="formData.urgentLinker"
						placeholder="请输入紧急联系人电话"
						@blur="validateField('urgentLinker')"
					/>
				</view>
				<view v-if="errors.urgentLinker" class="error-text">{{ errors.urgentLinker }}</view>
			</view>
			<!-- 上传人脸照片 -->
			<view class="form-item">
				<view class="label">
					<text class="label-text">上传人脸照片（正面清晰照片，方便健身房确认身份）</text>
					<text class="required">*</text>
				</view>
				<view class="upload-section">
					<view 
						class="upload-box" 
						:class="{ 'has-image': formData.faceImgUrl }"
						@click="chooseImage"
					>
						<image 
							v-if="formData.faceImgUrl" 
							:src="formData.faceImgUrl" 
							class="uploaded-image"
							mode="aspectFill"
						/>
						<view v-else class="upload-placeholder">
							<text class="upload-icon">+</text>
						</view>
					</view>
				</view>
				<view v-if="errors.faceImgUrl" class="error-text">{{ errors.faceImgUrl }}</view>
			</view>
			<!-- 出生日期 -->
			<view class="form-item">
				<view class="label">
					<text class="label-text">出生日期</text>
				</view>
				<wd-datetime-picker type="date" v-model="yearValue" @confirm="yearConfirm" :maxDate="Date.now()" :minDate="Date.now() - (31557600000*100)">
					<view class="input-wrapper">
						<input 
							class="input-field"
							disabled
							v-model="formData.birth"
							placeholder="请选择出生日期"
							@blur="validateField('birth')"
						/>
					</view>
				</wd-datetime-picker>
				<view v-if="errors.birth" class="error-text">{{ errors.birth }}</view>
			</view>
			
			<!-- 职业 -->
			<view class="form-item">
				<view class="label">
					<text class="label-text">职业</text>
				</view>
				<view class="input-wrapper">
					<input 
						class="input-field"
						v-model="formData.career"
						placeholder="请输入职业"
						@blur="validateField('career')"
					/>
				</view>
				<view v-if="errors.career" class="error-text">{{ errors.career }}</view>
			</view>
			
			<!-- 国籍 -->
			<view class="form-item">
				<view class="label">
					<text class="label-text">国籍</text>
				</view>
				<view class="input-wrapper">
					<input 
						class="input-field"
						v-model="formData.nationality"
						placeholder="请输入国籍"
						@blur="validateField('nationality')"
					/>
				</view>
				<view v-if="errors.nationality" class="error-text">{{ errors.nationality }}</view>
			</view>
			
			<!-- 电子邮箱 -->
			<view class="form-item">
				<view class="label">
					<text class="label-text">电子邮箱</text>
				</view>
				<view class="input-wrapper">
					<input 
						class="input-field"
						v-model="formData.email"
						placeholder="请输入邮箱"
						@blur="validateField('email')"
					/>
				</view>
				<view v-if="errors.email" class="error-text">{{ errors.email }}</view>
			</view>
			
			<!-- 联系地址 -->
			<view class="form-item">
				<view class="label">
					<text class="label-text">联系地址</text>
				</view>
				<view class="input-wrapper">
					<input 
						class="input-field"
						v-model="formData.address"
						placeholder="请输入联系地址"
						@blur="validateField('address')"
					/>
				</view>
				<view v-if="errors.address" class="error-text">{{ errors.address }}</view>
			</view>
		</view>
		<!-- 性别弹窗 -->
		<wd-action-sheet v-model="show3" z-index="999" cancel-text="取消" :actions="genderOptions" @close="show3=false" @select="GenderPicker" />
		<!-- 底部按钮 -->
		<view class="bottom-action" v-if="formData?.status == 0">
			<button 
				class="submit-btn"
				:class="{ 'loading': submitLoading2 }"
				@click="handleSubmit"
			>
				<text class="btn-text">{{ submitLoading2 ? '提交中...' : '签署协议' }}</text>
			</button>
		</view>
		<view class="bottom-action" v-else>
			<button 
				class="submit-btn"
				:class="{ 'loading': submitLoading2 }"
				@click="handleSubmit2"
			>
				<text class="btn-text"> 立即购买 </text>
			</button>
		</view>
	  <fui-loading type="col" v-if="loadActive" :isFixed="true" :isMask="true"></fui-loading>
	</view>
</template>

<script setup>
    import { useUserStore } from '@/store/user'
	const userStore = useUserStore()
	import { useUpload } from '@/uni_modules/wot-design-uni'
	const { startUpload, abort, chooseFile, UPLOAD_STATUS } = useUpload()
	const userInfo = ref(userStore.userInfo);
	// const signInfo = ref({signFlowId: "61628f9c59f640c49d45b3855c042e8e"});
	const signInfo = ref({});
	
	
	// 提交加载状态
	const loadActive = ref(false);
	const submitLoading = ref(false);
	const submitLoading2 = ref(false);
	const activeIndex1 = ref(0);
	// 计划类型
	const planType = ref('');
	// 场馆id
	const venueId = ref('');
	const show3 = ref(false);
	const yearValue = ref(Date.now() - (31557600000*18));
	
	// 性别选项
	const genderOptions = ref([
		{ name: '男', value: '1' },
		{ name: '女', value: '2' },
	])
	
	// 表单数据
	const formData = ref({
		name: '',              // 姓名
		phone: '',             // 手机号码
		idcard: '',            // 身份证号码
		sex: '',            // 性别
		urgentLinker: '',  // 紧急联系人
		faceImgUrl: '',         // 人脸照片
		birth: '',         // 出生日期
		career: '',        // 职业
		nationality: '',       // 国籍
		email: '',             // 电子邮箱
		address: ''            ,// 联系地址
		status: 0,            // 状态
	})
	
	// 错误信息
	const errors = ref({
		name: '',
		phone: '',
		idcard: '',
		sex: '',
		urgentLinker: '',
		faceImgUrl: '',
		birth: '',
		career: '',
		nationality: '',
		email: '',
		address: ''
	})
	
	/**
	 * ==================== 方法定义 ====================
	 */
	
	/**
	 * 验证单个字段
	 * @param {string} field - 字段名
	 */
	const validateField = (field) => {
		const value = formData.value[field]
		
		// 清空之前的错误信息
		errors.value[field] = ''
		
		switch (field) {
			case 'name':
				if (!value) {
					errors.value.name = '请输入姓名'
				} else if (value.length < 2 || value.length > 10) {
					errors.value.name = '姓名长度在2到10个字符'
				}
				break
				
			case 'phone':
				if (!value) {
					errors.value.phone = '请输入手机号码'
				} else if (!/^1[3-9]\d{9}$/.test(value)) {
					errors.value.phone = '请输入正确的手机号码'
				}
				break
				
			case 'idcard':
				if (!value) {
					errors.value.idcard = '请输入身份证号码'
				} else if (!/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value)) {
					errors.value.idcard = '请输入正确的身份证号码'
				}
				break
				
			case 'sex':
				if (!value) {
					errors.value.sex = '请选择性别'
				}
				break
				
			case 'urgentLinker':
				if (!value) {
					errors.value.urgentLinker = '请输入紧急联系人'
				} else if (!/^1[3-9]\d{9}$/.test(value)) {
					errors.value.phone = '请输入正确的紧急联系人手机号码'
				}
				break
				
			case 'faceImgUrl':
				if (!value) {
					errors.value.faceImgUrl = '请上传人脸照片'
				}
				break
				
			case 'birth':
				// 出生日期为可选字段，不做必填验证
				break
				
			case 'career':
				// 职业为可选字段，不做必填验证
				break
				
			case 'nationality':
				// 国籍为可选字段，不做必填验证
				break
				
			case 'email':
				// 邮箱为可选字段，但如果填写了需要验证格式
				if (value && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
					errors.value.email = '请输入正确的邮箱格式'
				}
				break
				
			case 'address':
				// 联系地址为可选字段，不做必填验证
				break
		}
	}
	
	/**
	 * 验证所有字段
	 */
	const validateAllFields = () => {
		validateField('name')
		validateField('phone')
		validateField('idcard')
		validateField('sex')
		validateField('urgentLinker')
		validateField('faceImgUrl')
		validateField('birth')
		validateField('career')
		validateField('nationality')
		validateField('email')
		validateField('address')
		// 检查是否有错误
		return !Object.values(errors.value).some(error => error !== '')
	}
	
	/**
	 * 选择图片
	 */
	const chooseImage = () => {
		uni.chooseImage({
			count: 1,
			sizeType: ['compressed'],
			sourceType: ['camera', 'album'],
			success: (res) => {
				const tempFilePath = res.tempFilePaths[0]
				// TODO: 上传图片到服务器
				loadActive.value = true;
				uploadImage(tempFilePath)
			},
			fail: (err) => {
				console.error('选择图片失败:', err)
				uni.showToast({
					title: '选择图片失败',
					icon: 'none',
					duration: 2000
				})
			}
		})
	}
	
	/**
	 * 上传图片到服务器
	 * @param {string} filePath - 图片路径
	 */
	const uploadImage = async (filePath) => {
		const file = {
			url: filePath,
			status: UPLOAD_STATUS.PENDING,
			percent: 0
		}
		startUpload(file, {
			action: `${getApp().globalData.baseUrl}/v4/vip/uploadImgFile`,
			 formData:{
			  accessToken:userInfo.value.authenticationToken
		  },
			onSuccess(res) {
				const data = JSON.parse(res.data);
				if(data.code==0){
					// 设置图片路径
					formData.value.faceImgUrl = data.data.key
					// 清空错误信息
					errors.value.faceImgUrl = '';
			    	loadActive.value = false;
				}
			},
			onError(err) {
				console.log('上传失败', err) 
			    loadActive.value = false;

			},
			onProgress(progress) {
				console.log('上传进度', progress)
			}
		})
	}
	
	// 显示性别选择器
	const GenderPicker = (e) => {
		 formData.value.sex = e.index+1;
	}
	
	// 年龄选择器
	const yearConfirm = (e) => {
		if(e.value){
			const birth =  uni.$uv.timeFormat(e.value,'yyyy-mm-dd');
			formData.value.birth = birth
		}
	}
	/**
	 * 表单提交
	 */
	const handleSubmit = async () => {
		try {
			if(submitLoading2.value)return;
			// 表单验证
			const isValid = validateAllFields()
			if (!isValid) {
				uni.showToast({
					title: '请检查表单信息',
					icon: 'none',
					duration: 2000
				})
				return
			}
			submitLoading2.value = true;
			uni.api.createChangeApply({
				...formData.value,
				venueId: venueId.value,
				planType: planType.value,
				isWxLite:1,
			}).then(res => {
			  if (res.code == 0) {
				  signInfo.value = res.data;
				  if(planType.value != 3){ // ！=年卡 直接购买
					  handleSubmit2();
				  }else{
					  uni.navigateTo({
					  	url: `/pagesA/view/openVip/vipWeb?url=${encodeURIComponent(res.data.signUrl)}`
					  })
				  }
			  }
			}).finally(() => {
				submitLoading2.value = false
			})
			// TODO: 调用提交API
			// const params = {
			//   name: formData.value.name,
			//   phone: formData.value.phone,
			//   idcard: formData.value.idcard,
			//   emergencyPhone: formData.value.emergencyPhone,
			//   faceImgUrl: formData.value.faceImgUrl
			// }
			// const result = await uni.api.submitCourseData(params)
			// 去支付

		} catch (error) {
			console.error('表单提交失败:', error)
			uni.showToast({
				title: '提交失败，请重试',
				icon: 'none',
				duration: 2000
			})
		} finally {
			submitLoading.value = false
		}
	}
	
	/**
	 * 表单提交
	 */
	const handleSubmit2 = async () => {
			const params = {
				  planType:planType.value,
				  venueId: venueId.value,
				  signFlowId: signInfo.value.signFlowId,
			}
			uni.navigateTo({
				url:`/pagesA/view/openVip/pay?params=${JSON.stringify(params)}`
			})
			
	}
	/**
	 * 重置表单
	 */
	const resetForm = () => {
		formData.value = {
			name: '',
			phone: '',
			idcard: '',
			sex: '',
			urgentLinker: '',
			faceImgUrl: '',
			birth: '',
			career: '',
			nationality: '',
			email: '',
			address: ''
		}
		errors.value = {
			name: '',
			phone: '',
			idcard: '',
			sex: '',
			urgentLinker: '',
			faceImgUrl: '',
			birth: '',
			career: '',
			nationality: '',
			email: '',
			address: ''
		}
	}
	
	/**
	 * ==================== 生命周期 ====================
	 */
	const getUser = ()=>{
		loadActive.value = true;
		uni.api.getChangeApplyDetail().then(res => {
		  if (res.code == 0) {
			if(res.data?.faceUrl){
				activeIndex1.value = 1;
			}else{
				activeIndex1.value = 0;
			}
			Object.keys(res.data).forEach(key => {
				if (res.data[key]) {
					formData.value[key] = res.data[key]
				}
			})
			formData.value.hasOldFaceImg = res.data?.faceImgUrl?1:0;
			formData.value.faceImgUrl = res.data?.faceUrl;
		  }
		  loadActive.value = false;
		});
	}
	onLoad((opt) => {
		planType.value = opt.planType;
		venueId.value = opt.venueId;
		getUser();
	})
	onShow(() => {
		if(signInfo.value?.signFlowId){
			loadActive.value = true;
			uni.api.getChangeApplyDetail({
				 signFlowId:signInfo.value.signFlowId
			}).then(res => {
			  if (res.code == 0) {
				if(res.data.status==1){
					activeIndex1.value = 2;
					formData.value.status = res.data.status;
				}
			  }
			  loadActive.value = false;
			});
		}
	})
</script>

<style lang="scss" scoped>
	.page {
		min-height: 100vh;
		background-color: #f3f4fb;
		padding-bottom: 120rpx; // 为底部按钮留出空间
	}

	// 步骤指示器
	.step-indicator {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 40rpx 30rpx;
		background-color: #fff;
		margin-bottom: 20rpx;
		
		.step-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			flex: 1;
			position: relative;
			
			&:not(:last-child)::after {
				content: '';
				position: absolute;
				top: 20rpx;
				right: -50%;
				width: 100%;
				height: 2rpx;
				background-color: #e8e8e8;
				z-index: 1;
			}
			
			&.active {
				.step-number {
					background-color: #4285f4;
					color: #fff;
				}
				
				.step-text {
					color: #4285f4;
				}
			}
			
			.step-number {
				width: 40rpx;
				height: 40rpx;
				border-radius: 50%;
				background-color: #e8e8e8;
				color: #999;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 24rpx;
				font-weight: 500;
				margin-bottom: 12rpx;
				position: relative;
				z-index: 2;
			}
			
			.step-text {
				font-size: 24rpx;
				color: #999;
			}
		}
	}

	// 表单区域
	.form-section {
		padding: 0 30rpx;
		.form-item {
			margin-bottom: 40rpx;
			
			// 标签区域
			.label {
				display: flex;
				align-items: center;
				margin-bottom: 16rpx;
				
				.label-text {
					font-size: 28rpx;
					color: #333;
					font-weight: 500;
				}
				
				.required {
					color: #ff4757;
					font-size: 28rpx;
					margin-left: 4rpx;
				}
			}
			
			// 输入框容器
			.input-wrapper {
				.input-field {
					width: 100%;
					height: 88rpx;
					background-color: #fff;
					border: 2rpx solid #e8e8e8;
					border-radius: 8rpx;
					padding: 0 24rpx;
					font-size: 28rpx;
					color: #333;
					box-sizing: border-box;
					
					&::placeholder {
						color: #ccc;
					}
					
					&:focus {
						border-color: #666;
						outline: none;
					}
				}
				.input-field2 {
					width: 100%;
					height: 88rpx;
					line-height: 88rpx;
					background-color: #fff;
					border: 2rpx solid #e8e8e8;
					border-radius: 8rpx;
					padding: 0 24rpx;
					font-size: 28rpx;
					color: #808080;
					box-sizing: border-box;
					
				}
			}
			
			// 上传区域
			.upload-section {
				.upload-box {
					width: 200rpx;
					height: 200rpx;
					background-color: #fff;
					border: 2rpx dashed #e8e8e8;
					border-radius: 8rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					transition: all 0.3s ease;
					
					&.has-image {
						border-style: solid;
						border-color: #666;
					}
					
					.uploaded-image {
						width: 100%;
						height: 100%;
						border-radius: 6rpx;
					}
					
					.upload-placeholder {
						.upload-icon {
							font-size: 60rpx;
							color: #ccc;
							font-weight: 300;
						}
					}
				}
			}
			
			// 错误信息
			.error-text {
				font-size: 24rpx;
				color: #ff4757;
				margin-top: 8rpx;
				padding-left: 4rpx;
			}
		}
	}

	// 底部操作区
	.bottom-action {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		padding: 30rpx;
		border-top: 1rpx solid #f0f0f0;
		z-index: 10;
		.submit-btn {
			width: 100%;
			height: 88rpx;
			background-color: #000;
			border: none;
			border-radius: 8rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			transition: all 0.3s ease;
			
			&.loading {
				background-color: #666;
			}
			
			&:active {
				background-color: #333;
			}
			
			.btn-text {
				font-size: 32rpx;
				color: #fff;
				font-weight: 500;
			}
		}
	}
</style>